﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Infrastructure;

namespace Infrastructure.Extend
{
    /// <summary>
    /// 数据表扩展
    /// <remarks></remarks>
    /// </summary>
    public static class DataTableExtend
    {
        /// <summary>
        /// 转换为匿名动态对象的列表
        /// </summary>
        /// <param name="table">表</param>
        /// <returns></returns>
        public static List<dynamic> ToList(this DataTable table)
        {
            var list = new List<dynamic>();
            var rows = table.Rows;

            if (rows.Count == 0)
            {
                return list;
            }

            var columns = table.Columns;
            var type = DynamicType.CreateType(DynamicType.Property.FromColumns(columns));

            foreach (DataRow row in rows)
            {
                var instance = Activator.CreateInstance(type);
                for (int i = 0; i < columns.Count; i++)
                {
                    if (System.DBNull.Value != row[i])
                    {
                        type.GetProperty(columns[i].ColumnName).SetValue(instance, row[i], null);
                    }
                }
                list.Add(instance);
            }
            return list;
        }

        /// <summary>
        /// 转换为对象的列表
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="table">表</param>
        /// <returns></returns>
        public static List<T> ToList<T>(this DataTable table) where T : class,new()
        {
            var type = typeof(T);
            var list = new List<T>();

            foreach (DataRow row in table.Rows)
            {
                var instance = new T();

                for (int i = 0; i < table.Columns.Count; i++)
                {
                    if (System.DBNull.Value != row[i])
                    {
                        var p = type.GetProperty(table.Columns[i].ColumnName);
                        if (p != null)
                        {
                            p.SetValue(instance, row[i], null);
                        }
                    }
                }
                list.Add(instance);
            }
            return list;
        }


        /// <summary>
        /// 转换为Json
        /// </summary>
        /// <param name="table">表</param>
        /// <returns></returns>
        public static string ToJson(this DataTable table)
        {
            return JsonSerializer.ToJson(table);
        }
    }
}
